// utils/http.ts
import Taro from '@tarojs/taro'
// import {useUserStore} from "@/stores/index";
import { buildUrlParams } from './tooler';
import { apiConfig } from "@/utils/config";

// const userStore = useUserStore();

// 定义基础配置类型
interface RequestConfig {
  baseURL?: string
  timeout?: number
  headers?: Record<string, string>
}

// 定义请求选项类型
interface RequestOptions {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
  data?: any
  headers?: Record<string, string>
  loadingText?: string
  showLoading?: boolean
}

// 定义响应类型
interface ResponseData<T = any> {
  code: number
  message: string
  data: T
}

class HttpRequest {
  private config: RequestConfig

  constructor(config: RequestConfig = {}) {
    this.config = {
      baseURL: config.baseURL || '', // 基础路径
      timeout: config.timeout || 15000, // 默认15秒超时
      headers: {
        'Content-Type': 'application/json',
        ...(config.headers || {})
      }
    }
  }

  /**
   * 核心请求方法
   */
  private async request<T>(options: RequestOptions): Promise<ResponseData<T>> {
    const { showLoading = true, loadingText = '加载中...' } = options

    // 显示加载提示
    if (showLoading) {
      Taro.showLoading({
        title: loadingText,
        mask: true
      })
    }

    try {
      // 合并请求配置
      const headerData: any = {
        'Authorization': Taro.getStorageSync('token') || '',
        ...this.config.headers,
        ...(options.headers || {})
      }

      if (options.url.includes('getToken')) {
        delete headerData['token'];
        headerData['Token'] = '1'
      }
      console.log('headerData', headerData)
      const mergedOptions: Taro.request.Option = {
        url: this.config.baseURL + options.url,
        method: options.method || 'GET',
        data: options.data || {},
        header: headerData,
        timeout: this.config.timeout
      }

      // 发起请求
      const response = await Taro.request(mergedOptions)

      // 关闭加载提示
      if (showLoading) {
        Taro.hideLoading()
      }

      // 处理响应数据
      if (response.statusCode >= 200 && response.statusCode < 300) {
        return response.data as ResponseData<T>
      } else {
        throw this.handleError(response)
      }
    } catch (error) {
      // 关闭加载提示
      if (showLoading) {
        Taro.hideLoading()
      }
      throw this.handleError(error)
    }
  }

  /**
   * 错误处理方法
   */
  private handleError(error: any) {
    console.error('请求错误:', error)

    // 统一错误提示
    let errMsg = '请求失败，请稍后重试'
    if (error.errMsg) {
      errMsg = error.errMsg
    } else if (error.message) {
      errMsg = error.message
    }

    Taro.showToast({
      title: errMsg,
      icon: 'none',
      duration: 2000
    })

    return new Error(errMsg)
  }

  /**
   * GET 请求
   */
  public async get<T>(url: string, params?: any, options?: Omit<RequestOptions, 'url' | 'method' | 'data'>) {
    // 将参数拼接到URL上
    let queryString = ''
    if (params) {
      queryString = Object.keys(params)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('&')
      url += (url.includes('?') ? '&' : '?') + queryString
    }

    return this.request<T>({
      url,
      method: 'GET',
      ...options
    })
  }

  /**
   * POST 请求
   */
  public async post<T>(url: string, data?: any, options?: Omit<RequestOptions, 'url' | 'method' | 'data'>) {
    return this.request<T>({
      url,
      method: 'POST',
      data,
      ...options
    })
  }

  public async postQuery<T>(url: string, data?: any, options?: Omit<RequestOptions, 'url' | 'method' | 'data'>) {
    url = buildUrlParams(url, data);
    return this.request<T>({
      url,
      method: 'POST',
      data,
      ...options
    })
  }



  /**
   * PUT 请求
   */
  public async put<T>(url: string, data?: any, options?: Omit<RequestOptions, 'url' | 'method' | 'data'>) {
    return this.request<T>({
      url,
      method: 'PUT',
      data,
      ...options
    })
  }

  /**
   * DELETE 请求
   */
  public async delete<T>(url: string, data?: any, options?: Omit<RequestOptions, 'url' | 'method' | 'data'>) {
    return this.request<T>({
      url,
      method: 'DELETE',
      data,
      ...options
    })
  }

  public async upload(tempFilePath: string) {
    // const tempFilePath = res.tempFilePaths[0]; // 获取到选择的临时文件路径
    console.log('上传的临时文件路径:', tempFilePath);

    // 2. 上传图片
    const uploadRes = await Taro.uploadFile({
      url: apiConfig.baseURL + '/index.php/index/upload/index', // **替换成你的图片上传接口地址**
      filePath: tempFilePath,
      name: 'image', // 后端接收文件的字段名，通常是 'file' 或 'image'
      header: {
        'Content-Type': 'multipart/form-data',
        'Authorization': Taro.getStorageSync("token") // 如果需要认证，添加你的 token
      },
      formData: {
        // 如果需要传递额外的数据给后端，可以在这里添加
        'user_id': '123',
        'type': 'avatar'
      },
    });

    console.log('上传结果:', uploadRes);

    // 3. 处理上传结果
    if (uploadRes.statusCode === 200) {
      // 根据后端返回的数据结构解析，通常后端会返回图片的 URL
      const data = JSON.parse(uploadRes.data); // uploadRes.data 是一个字符串，需要解析
      if (data.error == 0) { // 假设后端返回 { code: 0, msg: 'success', url: '...' }
        const uploadedImageUrl = apiConfig.baseURL + data.url;
        console.log('上传成功，图片URL:', uploadedImageUrl);
        return uploadedImageUrl;
        // list.value.push(uploadedImageUrl);
        // shop.value.imgUrl = uploadedImageUrl;
        // Taro.showToast({ title: '上传成功', icon: 'success' });
      } else {
        // throw new Error(data.msg || '上传失败，服务器返回错误');
        return '';
      }
    } else {
      // throw new Error(`上传失败，状态码：${uploadRes.statusCode}`);
      return '';
    }
  }
}

// 创建默认实例
const http = new HttpRequest({
  baseURL: apiConfig.baseURL, // 替换为你的API基础地址
  timeout: apiConfig.timeout
})

export default http
